package procsim;

public class JKFlipFlop extends FlipFlop{
    private Signal inSigJ, inSigK;
    public JKFlipFlop(Signal inJ, Signal inK){
        super();
        if(inJ!=null) inJ.addElement(this);
        if(inK!=null) inK.addElement(this);
        inSigJ=inJ;
        inSigK=inK;
    }
    public JKFlipFlop(){
        super();
    }
    public JKFlipFlop setJSignal(Signal jsig){
        if(jsig!=null) jsig.addElement(this);
        inSigJ=jsig;
        return this;
    }
    public JKFlipFlop setKSignal(Signal ksig){
        if(ksig!=null) ksig.addElement(this);
        inSigK=ksig;
        return this;
    }
    @Override
    public JKFlipFlop tick(){
        int val=0;
        if(inSigJ!=null && inSigK!=null){
            if(inSigJ.get()==0 && inSigK.get()==0)
                val=outSigPrev.get();
            else if(inSigJ.get()==1 && inSigK.get()==0)
                val=1;
            else if(inSigJ.get()==0 && inSigK.get()==1)
                val=0;
            else
                val=outSigPrev.negate().get();
        }
        outSig.set(outSigPrev);
        if(outSigResult!=null) outSigResult.set(outSig);
        outSigPrev.set(val);
        calculateComplement();
        return this;
    }
    @Override
    public void updateSignal(Sig sig){
        if(ticking) return;
        if(inSigJ!=null && inSigJ==sig)
            inSigJ.set(sig.get(), false);
        if(inSigK!=null && inSigK==sig)
            inSigK.set(sig.get(), false);
    }
}
